import type { User, UserListResponse } from '~/types/user'
import StorageUtil from '@/utils/storage';
import { useApi } from '@/composables/useApi';

export const useUserApi = () => {
  const router = useRouter()

  // 统一错误处理
  // const handleError = (error: any) => {
  //   const message = error.data?.message || error?.message || 'Request failed'
  //   const code = error.statusCode || 500

  //   // 显示错误提示（可根据UI库调整）
  //   console.error(message)

  //   // 401 未授权跳转到登录页
  //   if (code === 401) {
  //     router.push('/login')
  //   }

  //   // 抛出格式化后的错误
  //   throw {
  //     code,
  //     message,
  //     data: error.data?.data || null
  //   }
  // }

  // 用户注册
  const register = async (userData: { username: string; password: string, role_id: number, disabled?: number }) => {
    try {
      const response = await $fetch('/api/register', {
        method: 'POST',
        body: userData,
        headers: {
          'Content-Type': 'application/json'
        }
      })
      // 显示成功提示
      // console.log('Registration successful')
      return response
    } catch (error) {
      // return handleError(error)
      console.error('获取数据失败:', error)
      throw error
    }
  }

  // 用户登录
  const login = async (credentials: { username: string; password: string }) => {
    try {
      const response = await $fetch<any>('/api/login', {
        method: 'POST',
        body: credentials,
        headers: {
          'Content-Type': 'application/json'
        }
      })

      // 存储两种 Token
      if (response?.data?.accessToken && response?.data?.refreshToken) {
        StorageUtil.set('access_token', response.data.accessToken)
        StorageUtil.set('refresh_token', response.data.refreshToken)
      }
      return response
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }

  const updateUser = async (userData: { password: string, role_id: number, disabled?: number }) => {
    try {
      const response = await useApi('/api/users', {
        method: 'PUT',
        body: userData,
        headers: {
          'Content-Type': 'application/json'
        }
      })
      // 显示成功提示
      return response
    } catch (error) {
      // return handleError(error)
      console.error('获取数据失败:', error)
      throw error
    }
  }
  // 获取用户列表 (带分页)
  const getUsers = async (page: number = 1, size: number = 10) => {
    try {
      return await useApi<UserListResponse>('/api/users', {
        // method: 'POST',
        query: { page, size },
        headers: {
          'Content-Type': 'application/json'
        }
      })
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }

  // 删除用户
  const deleteUser = async (id: string) => {
    try {
      return await useApi('/api/users', {
        method: 'DELETE',
        query: { id },
        headers: {
          'Content-Type': 'application/json'
        }
      })
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }

  // 获取单个用户
  const getUser = async (id: string) => {
    try {
      return await useApi<User>(`/api/users/${id}`, {
        headers: {
          'Content-Type': 'application/json'
        }
      })
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }

  // 切换用户状态
  const toggleUserStatus = async (id: string, disable: boolean) => {
    try {
      const response = await useApi(`/api/users/${id}/disable`, {
        method: 'PATCH',
        body: { disable: disable ? 1 : 0 },
        headers: {
          'Content-Type': 'application/json'
        }
      })

      // 显示操作提示
      console.log(`User ${disable ? 'disabled' : 'enabled'} successfully`)
      return response
    } catch (error) {
      console.error('获取数据失败:', error)
      throw error
    }
  }

  return {
    register,
    login,
    getUsers,
    getUser,
    toggleUserStatus,
    updateUser,
    deleteUser
  }
}